PATHMac OS 8 Developer Documentation > Operating System Services > Multiprocessing Services >

Adding Multitasking Capability to Applications Using Multiprocessing Services

   

Handling Periodic Actions

You can use notification mechanisms to do more than simply signal tasks. For example, Listing 3-5 shows a task that uses a semaphore to do periodic actions.

Listing 3-5   Using a semaphore to perform periodic actions

void MyTask(void) {

    MPSemaphoreID delay;

    MPCreateSemaphore(1, 0, &delay); // a binary semaphore
    while(true)
        {
            DoIt(); // do something interesting
            (void) MPWaitOnSemaphore(delay, 10 * kDurationMillisecond);
            }
    }

This example uses a semaphore solely to create a delay. After each call to the DoIt function, MyTask waits for a notification that never arrives and times out after 10ms.

You can combine the delaying and notification aspects of a semaphore to add more flexibility as shown in Listing 3-6 .

Listing 3-6   Performing actions periodically and on demand

main(void) {

    MPSemaphoreID delay;
    ...
    MPCreateSemaphore(2, 0, &delay);
    MPCreateTask(...);

    while(true) {
        // Event loop.

        if ( /* something important happened */ )
            {
                MPSignalSempahore(delay);
                }

            }
}

void MyTask(void) {

    while(true) {
        DoIt(); // Do interesting things.
        (void) MPWaitOnSemaphore(work, 100 * kDurationMillisecond);
        }
    }

In this example, the MyTask task runs essentially as before, except that the main application creates the semaphore. If no signal is sent to the semaphore, the DoIt function in MyTask executes every 100ms. However, in this example the application can signal the semaphore, which unblocks the task and allows the DoIt function to execute. That is, the DoIt function executes whenever the application signals the semaphore, or every 100ms otherwise.


© 1999 Apple Computer, Inc. – (Last Updated 07 May 99)